'use strict';
import React, { useState, useEffect, useRef } from 'react';
import { Collapse } from 'antd';
import {
  InfoCircleFilled,
  MessageFilled,
  PlusCircleFilled,
  BellFilled,
  FormatPainterFilled,
} from '@ant-design/icons';
import BaseInfo from './baseInfo';
import SignalAndMassage from './signal-and-massage';
import Task from './task';
import MultiInstance from './multiInstance';
import Listeners from './listeners';
import Properties from './properties';
import Other from './other';
import FlowCondition from './flow-condition';
import styles from './index.less';

/*
* 组件注释
* create by wuqiong
* creation time 2022/04/20
*
* */

const text = `
  A dog is a type of domesticated animal.
  Known for its loyalty and faithfulness,
  it can be found as a welcome guest in many households across the world.
`;
const { Panel } = Collapse;
const Index = (props) => {
  const { idEditDisabled, bpmnModeler, prefix, width } = props;

  const [activeKey, setActiveKey] = useState('base');
  const [elementId, setElementId] = useState("");
  const [elementType, setElementType] = useState("");
  const [elementBusinessObject, setElementBusinessObject] = useState({});
  const [conditionFormVisible, setConditionFormVisible] = useState(false);

  let timer = null;

  const callback = (key) => setActiveKey(key);

  const initModels = () => {
    // 初始化 modeler 以及其他 moddle
    if (!bpmnModeler) {
      // 避免加载时 流程图 并未加载完成
      timer = setTimeout(() => initModels(), 10)
      return
    }
    if (timer) clearTimeout(timer);
    window.bpmnInstances = {
      modeler: bpmnModeler,
      modeling: bpmnModeler.get('modeling'),
      moddle: bpmnModeler.get('moddle'),
      eventBus: bpmnModeler.get('eventBus'),
      bpmnFactory: bpmnModeler.get('bpmnFactory'),
      elementFactory: bpmnModeler.get('elementFactory'),
      elementRegistry: bpmnModeler.get('elementRegistry'),
      replace: bpmnModeler.get('replace'),
      selection: bpmnModeler.get('selection'),
    }

    getActiveElement()
  }
  const getActiveElement = () => {
    // 初始第一个选中元素 bpmn:Process
    initFormOnChanged(null)
    bpmnModeler.on('import.done', (e) => {
      initFormOnChanged(null)
    })
    // 监听选择事件，修改当前激活的元素以及表单
    bpmnModeler.on('selection.changed', ({ newSelection }) => {
      initFormOnChanged(newSelection[0] || null)
    })
    bpmnModeler.on('element.changed', ({ element }) => {
      // 保证 修改 "默认流转路径" 类似需要修改多个元素的事件发生的时候，更新表单的元素与原选中元素不一致。
      if (element && element.id === elementId) {
        initFormOnChanged(element)
      }
    })
  }
  // 初始化数据
  const initFormOnChanged = (element) => {
    let activatedElement = element
    if (!activatedElement) {
      activatedElement =
        window.bpmnInstances.elementRegistry.find(
          (el) => el.type === 'bpmn:Process'
        ) ??
        window.bpmnInstances.elementRegistry.find(
          (el) => el.type === 'bpmn:Collaboration'
        )
    }

    if (!activatedElement) return;

    window.bpmnInstances.bpmnElement = activatedElement

    const elementType = activatedElement.type.split(':')[1] || '';
    setElementId(activatedElement.id)
    setElementType(elementType)

    setElementBusinessObject(JSON.parse(
      JSON.stringify(activatedElement.businessObject)
    ))
    setConditionFormVisible(!!(
      elementType === 'SequenceFlow' &&
      activatedElement.source &&
      activatedElement.source.type.indexOf('StartEvent') === -1
    ))

    // setFormVisible(elementType === 'UserTask' || elementType === 'StartEvent')
  }

  useEffect(() => setActiveKey("base"), [elementId]);

  useEffect(() => {
    initModels();
    return () => window.bpmnInstances = null;
  }, []);

  return <div style={{ width }} className={styles.panel}>
    <Collapse activeKey={activeKey} onChange={callback} expandIconPosition={"end"} >
      <Panel header={<div className={styles.panelTabTitle}> <InfoCircleFilled className={styles.icon} />常规</div>} key="base">
        <BaseInfo idEditDisabled={idEditDisabled} type={elementType} businessObject={elementBusinessObject} />
      </Panel>
      <Panel style={{ display: elementType === 'Process' ? "block" : "none" }} header={<div className={styles.panelTabTitle}><MessageFilled className={styles.icon} />消息与信号</div>} key="message">
        <SignalAndMassage idEditDisabled={idEditDisabled} type={elementType} businessObject={elementBusinessObject} />
      </Panel>
      <Panel style={{ display: conditionFormVisible ? "block" : "none" }} header={<div className={styles.panelTabTitle}><InfoCircleFilled className={styles.icon} />流转条件</div>} key="condition">
        <FlowCondition businessObject={elementBusinessObject} type={elementType} />
      </Panel>
      <Panel style={{ display: elementType.indexOf('Task') !== -1 ? "block" : "none" }} header={<div className={styles.panelTabTitle}><InfoCircleFilled className={styles.icon} />任务</div>} key="task">
        <Task id={elementId} type={elementType} />
      </Panel>
      <Panel style={{ display: elementType.indexOf('Task') !== -1 ? "block" : "none" }} header={<div className={styles.panelTabTitle}><InfoCircleFilled className={styles.icon} />多实例</div>} key="multiInstance">
        <MultiInstance businessObject={elementBusinessObject} type={elementType} prefix={prefix} />
      </Panel>
      <Panel header={<div className={styles.panelTabTitle}><BellFilled className={styles.icon} />执行监听器</div>} key="listeners">
        <Listeners id={elementId} type={elementType} width={width} prefix={prefix} />
      </Panel>
      <Panel style={{ display: elementType === "UserTask" ? "block" : "none" }} header={<div className={styles.panelTabTitle}><BellFilled className={styles.icon} />任务监听器</div>} key="taskListeners">
        <Listeners id={elementId} componentType="task" type={elementType} width={width} prefix={prefix} />
      </Panel>
      <Panel header={<div className={styles.panelTabTitle}><PlusCircleFilled className={styles.icon} />扩展属性</div>} key="extensions">
        <Properties id={elementId} type={elementType} width={width} prefix={prefix} />
      </Panel>
      <Panel header={<div className={styles.panelTabTitle}><InfoCircleFilled className={styles.icon} />其他</div>} key="other">
        <Other id={elementId} />
      </Panel>
    </Collapse>
  </div >
};
export default Index;